import { obtainingImages } from '../../api/api'
import { _path, _item, _yaml } from '../../mode/allapi'

export let enmy = [
  {
    name: '路人甲',
    type: '武将',
    atk: 150,
    iq: 150,
    def: 150,
    hp: 0,
    maxHp: 0,
    num: 1,
    level: 1
  },
  {
    name: '路人乙',
    type: '武将',
    atk: 150,
    iq: 150,
    def: 150,
    hp: 0,
    maxHp: 0,
    num: 1,
    level: 1
  },
  {
    name: '路人丙',
    type: '武将',
    atk: 150,
    iq: 150,
    def: 150,
    hp: 0,
    maxHp: 0,
    num: 1,
    level: 1
  },
  {
    name: '路人丁',
    type: '武将',
    atk: 150,
    iq: 150,
    def: 150,
    hp: 0,
    maxHp: 0,
    num: 1,
    level: 1
  },
  {
    name: '路人戊',
    type: '武将',
    atk: 150,
    iq: 150,
    def: 150,
    hp: 0,
    maxHp: 0,
    num: 1,
    level: 1
  },
  {},
  {},
  {},
  {}
]

export async function setgenerate(player: any, enmyy: any, i: number) {
  if (i == 1) {
    for (let i = 0; i < enmy.length; i++) {
      if (enmy[i].name !== undefined) {
        enmy[i].hp = (player.DungeonStorey + 1) * 100
        enmy[i].maxHp = (player.DungeonStorey + 1) * 100
      }
    }
  }
  const wujian = player.wujian.map(obj =>
    obj && obj.name !== undefined && obj.hp !== undefined
      ? `${obj.name} (${obj.hp})`
      : ' '
  )
  if (enmyy) enmy = enmyy
  const enmys = enmy.map(obj =>
    obj && obj.name !== undefined && obj.hp !== undefined
      ? `${obj.name} (${obj.hp})`
      : ' '
  )
  const datas = {
    player: wujian,
    enmy: enmys
  }
  const imgs = await obtainingImages(
    '/resources/html/shuangfang/shuangfang.html',
    datas
  )
  return { imgs, enmy }
}

export async function addnum(player: any, win: any) {
  const log = []
  let reward = 0
  if (win.win == 'enmywin') {
    reward = (player.DungeonStorey + 1) * 100
    player.DungeonStorey += 1
    player.food_num += reward
    player.stone_num += reward
    player.wood_num += reward
    player.iron_num += reward
    log.push(`恭喜主公获得了胜利,缴获粮草、木材、石料、铁矿各${reward}`)
  } else {
    log.push(`很遗憾,主公军队溃败`)
  }
  return log
}

export async function addexper(player: any, enmy: any, win: any, hp: any) {
  for (let i = 0; i < player.wujian.length; i++) {
    if (player.wujian[i].name) {
      player.wujian[i].hp = hp[i]
    }
  }
  const player_level = player.wujian.reduce(
    (sum: any, element: { name: any; level: any }) =>
      element.name ? sum + element.level : sum,
    0
  )
  const enmy_level = enmy.reduce(
    (sum: any, element: { name: any; level: any }) =>
    element.name ? sum + element.level : sum,
    0
  )
  let exp = Math.round((0.5+(enmy_level - player_level) / 100) * win)
  if (exp <= 0) {
    exp = Math.floor(Math.random() * 5) + 1
  }
  for (const element of player.wujian) {
    if (element.name) {
      element.nowexp += exp
      while (element.nowexp >= element.needexp) {
        element.level += 1
        element.nowexp -= element.needexp
        for (const el of player.wujian) {
          const nextlevel = '-' + el.level
          const nextexp = (await _yaml()).upsilver.find(item => item['武将'])[
            '武将'
          ][nextlevel]
          if (nextexp) {
            el.needexp = nextexp
          }
        }
        element.atk =
          Math.round(element.atk * 100 + element.increase_atk * 100) / 100
        element.iq =
          Math.round(element.iq * 100 + element.increase_iq * 100) / 100
        element.def =
          Math.round(element.def * 100 + element.increase_def * 100) / 100
        element.maxHp = element.level * 200 - 100
      }
    }
  }
}

export async function zhandou(win: any) {
  const zhandou = win.zhandou
  const data = {
    Zhandou: zhandou
  }
  const img = await obtainingImages(
    '/resources/html/zhandou/zhandou.html',
    data
  )
  return img
}

export async function setenmy(action: any, id: string) {
  let enmy = []
  if (action.cordon == 0) {
    enmy = [{}, {}, {}, {}, {}, {}, {}, {}, {}]
    const fand = await _item(id, 'bing')
    const selectedIds = []
    const indexOrder = [4, 2, 1, 0, 5, 3, 8, 6, 7]
    for (let i = 0; i < action.grade; i++) {
      let randomNum: any
      do {
        const min = 2001
        const max = 2075
        randomNum = Math.floor(Math.random() * (max - min + 1)) + min
      } while (selectedIds.includes(randomNum))
      selectedIds.push(randomNum)
      const enmyInfo = await fand.find(item => item.id == randomNum)
      enmyInfo.level = Math.min(action.hit+1, 50)
      enmyInfo.atk += enmyInfo.increase_atk * (enmyInfo.level - 1)
      enmyInfo.iq += enmyInfo.increase_iq * (enmyInfo.level - 1)
      enmyInfo.def += enmyInfo.increase_def * (enmyInfo.level - 1)
      enmy[indexOrder[i]] = enmyInfo
    }
    action.cordon = enmy
    action.troops = (action.hit + 1) * 300
    for (let i = 0; i < action.cordon.length; i++) {
      if (Object.keys(action.cordon[i]).length > 0) {
        action.cordon[i].hp = action.troops
      }
    }
  } else {
    enmy = action.cordon
  }
  return enmy
}

export async function levy(player:any){
  const currentTime = new Date().getTime()
  const lastTime = player.time
  const minutes = Math.floor((currentTime - lastTime) / 60000)
  const resources = ['food', 'stone', 'wood', 'iron', 'currency']
  resources.forEach(resource => {
    const production = (player[resource + '_production'] * minutes) / 60
    if (
      player[resource + '_num'] + Math.round(production) >=
      player[resource + '_max']
    ) {
      player[resource + '_num'] = player[resource + '_max']
    } else {
      player[resource + '_num'] += Math.round(production)
    }
  })
  player.time = currentTime
}

export async function rivalsettlement(rival:any, action:any) {
  rival.food_production -= action.food
  rival.stone_production -= action.stone
  rival.wood_production -= action.wood
  rival.iron_production -= action.iron
  rival.havecity -= 1
}

export async function settlement(player: any, action: any) {
  const log = []
  action.belong = player.user_id
  action.hit += 1
  action.cordon = 0
  action.troops = 0
  player.food_num += action.food
  player.stone_num += action.stone
  player.wood_num += action.wood
  player.iron_num += action.iron
  log.push(
    `恭喜主公获得胜利,成功攻占${action.name}\n缴获粮草${action.food},木材${action.wood},石料${action.stone},铁矿${action.iron}`)
  player.food_production += action.food
  player.stone_production += action.stone
  player.wood_production += action.wood
  player.iron_production += action.iron
  player.havecity += 1
  return log
}

export async function jian(wujiang:any){
  const logs = []
  if (wujiang[4] == undefined || wujiang[4].name == undefined) {
     logs.push(`阵法未配置主将，无法进入战斗`)
  }
  for (let i = 0; i < wujiang.length; i++) {
    if (wujiang[i].name != undefined && wujiang[i].hp <= 0) {
      if (i == 4) {
         logs.push(`主将未领兵，无法进入战斗`)
      }
    }
  }
  return logs
}

export async function zhencha(action: any){
  let guishu = action.belong
  const log = []
  const shoujun = await action.cordon
  .reduce((acc, item, index) => {
    if (Object.keys(item).length > 0) {
      const str =
        index == 4
          ? `【${item.name}】(${item.hp})`
          : `${item.name} (${item.hp})`
      acc.push(str)
    }
    return acc
  }, [])
  .join(', ')
if (action.belong == '0') {
  guishu = '无'
} else {
  const player = await (await _path(guishu)).player
  guishu = player.name
}
const output = `\n粮草${action.food}/h\n木材${action.wood}/h\n石料${action.stone}/h\n铁矿${action.iron}/h\n`
let bingli = 0
for (let i = 0; i < action.cordon.length; i++) {
  if (Object.keys(action.cordon[i]).length > 0) {
    bingli += action.cordon[i].hp
  }
}
log.push(
  `${await action.name}\n归属:${guishu}\n等级:${action.grade}\n兵力：${bingli}\n防守：${shoujun}\n产出：${output}`
)

return log
}
